// ~ CopyRight © 2012 USTC SINOVATE  SOFTWARE CO.LTD All Rights Reserved.
package com.cmcc.zysoft.sysmanage.service;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import com.cmcc.zysoft.infocollection.constant.Constant;
import com.cmcc.zysoft.infocollection.model.Employee;
import com.cmcc.zysoft.infocollection.model.Role;
import com.cmcc.zysoft.infocollection.model.SystemUser;
import com.cmcc.zysoft.infocollection.util.MD5Tools;
import com.cmcc.zysoft.infocollection.util.UUIDUtil;
import com.cmcc.zysoft.sysmanage.dao.SystemUserPCDao;
import com.cmcc.zysoft.sysmanage.service.CompanyService;
import com.cmcc.zysoft.sysmanage.service.DepartmentService;
import com.cmcc.zysoft.sysmanage.service.RoleService;
import com.cmcc.zysoft.sysmanage.service.SysEmployeeService;
import com.cmcc.zysoft.sysmanage.service.UserRoleService;
import com.starit.common.dao.hibernate.HibernateBaseDao;
import com.starit.common.dao.service.BaseServiceImpl;
import com.starit.common.dao.support.Pagination;

/**
 * @author yandou
 */
@Service
public class SystemUserPCService extends BaseServiceImpl<SystemUser, String> {

	/**
	 * 属性名称：systemUserPCDao 类型：SystemUserPCDao
	 */
	@Resource
	private SystemUserPCDao systemUserPCDao;
	
	/**
	 * 属性名称：companyService 类型：CompanyService
	 */
	@Resource
	private CompanyService companyService;//公司管理
	
	/**
	 * 属性名称：departmentService 类型：DepartmentService
	 */
	@Resource
	private DepartmentService departmentService;//部门管理
	
	/**
	 * 属性名称：roleService 类型：RoleService
	 */
	@Resource
	private RoleService roleService;//角色
	
	/**
	 * 属性名称：userRoleService 类型：UserRoleService
	 */
	@Resource
	private UserRoleService userRoleService;//用户角色
	
	/**
	 * 属性名称：sysEmployeeService 类型：SysEmployeeService
	 */
	@Resource
	private SysEmployeeService sysEmployeeService;//雇员信息
	
	@Override
	public HibernateBaseDao<SystemUser, String> getHibernateBaseDao() {
		return systemUserPCDao;
	}

	/**
	 * 修改用户信息
	 * @param systemUser 返回类型：void
	 */
	public void updateSystemUser(SystemUser systemUser){
		systemUserPCDao.updateSystemUser(systemUser);
	}

	/**
	 * 保存用户信息 
	 * @param systemUser
	 * @param roleId 
	 * @param roleId 
	 */
	public void saveSystemUser(SystemUser systemUser, String userRoleId, String roleId) {
		String passSalt = UUIDUtil.generateUUID();
		systemUser.setDelFlag("0");
		systemUser.setPassSalt(passSalt);
		systemUser.setPassword(MD5Tools.encodePassword(systemUser.getPassword(),passSalt));
		Role role = this.roleService.getEntity(roleId);
		if(StringUtils.hasText(userRoleId)){
			this.updateEntity(systemUser);
			userRoleService.updateUserRole(userRoleId,role);
		}else{
			this.systemUserPCDao.save(systemUser);
			//用户角色处理
			userRoleService.save(role, systemUser);
		}
	}
	
	/**
	 * 保存系统用户
	 * 
	 * @param systemUser
	 * @return 返回类型：String
	 */
	public String saveSystemUser(SystemUser systemUser){
		return systemUserPCDao.saveSystemUser(systemUser);
	}

	/**
	 * 公司部门树
	 * @return
	 */
	public List<Map<String, Object>> companyDeptTree() {
		List<Map<String,Object>> companyTree = this.companyService.companyTree("0");
		return companyDeptChildrenTree(companyTree);
	}
	
	/**
	 * 根据员工实体找到用户实体
	 * @param employee
	 * @return
	 */
	@Transactional
	public SystemUser getUserByEmployee(Employee employee ){
		List<SystemUser> list = this.findByNamedParam(new String[]{"employeeId", "delFlag"}, new Object[]{employee.getEmployeeId(), "0"});
		if(null != list && !list.isEmpty()) {
			return list.get(0);
		} else {
			return null;
		}
	}
	
	@Transactional
	public SystemUser getUserByuserName(String username ){
		List<SystemUser> list = this.findByNamedParam(new String[]{"userName", "delFlag"}, new Object[]{username, "0"});
		if(null != list && !list.isEmpty()) {
			return list.get(0);
		} else {
			return null;
		}
	}
	
	/**
	 * 获取公司部门树辅助方法
	 * @param list
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Map<String,Object>> companyDeptChildrenTree(List<Map<String,Object>> list){
		for(Map<String,Object> map : list){
			//添加公司下面的部门
			String companyId = map.get("id").toString();
			List<Map<String,Object>> deptList = this.departmentService.deptTreeByCompanyId(companyId);//根据公司id获取下面的部门
			Object obj = map.get("children");//获取子公司
			if(null != obj){
				List<Map<String,Object>> companyList = (List<Map<String, Object>>)obj;
				companyDeptChildrenTree(companyList);
				if(!deptList.isEmpty()){
					if(companyList.addAll(deptList)){
						map.put("children", companyList);
					}
				}
			}else{
				if(!deptList.isEmpty()){
					map.put("children", deptList);
					map.put("state", "closed");
				}
			}
		}
		return list;
	}

	public String uploadPhoto(HttpServletRequest request,MultipartFile photoFile) {
		//在这里就可以对file进行处理了，可以根据自己的需求把它存到数据库或者服务器的某个文件夹  
        String filename = photoFile.getOriginalFilename();
        String extName = filename.substring(filename.lastIndexOf(".")).toLowerCase(); 
        try {
        	if(extName.trim().equals(".gif")||extName.trim().equals(".jpg")||extName.trim().equals(".jpeg")||extName.trim().equals(".png")||extName.trim().equals(".bmp")){
    	        String lastFileName = System.currentTimeMillis()+extName;
    	        String path = "/resources/image/upload/systemUserPhoto/";
    	        //图片存储的相对路径   
    	        String fileFullPath = request.getServletContext().getRealPath("")+path+lastFileName;
    			FileCopyUtils.copy(photoFile.getBytes(),new File(fileFullPath));  
    			return "/"+path.substring(1)+lastFileName;
            }else{
            	return "ERROR";
            }
		} catch (Exception e) {
			return "ERROR";
		}
	}
	
	
	/**
	 * 获取所有用户信息
	 * @return
	 */
	public Pagination<Object> getAllUser(int page, int rows ,String departmentid) {
		return this.systemUserPCDao.getAllUser(page, rows ,departmentid);
	}
	
	/**
	 * 判断用户名是否同名
	 * @param 
	 * @return true表示同名   false表示不同名
	 */
	public boolean isUserNameEqual(String userName,String userId){
		return this.systemUserPCDao.isUserNameEqual( userName, userId);
	}
	
	/**
	 * 判断手机号码是否存在
	 * @param 
	 * @return true表示同名   false表示不同名
	 */
	public boolean isPhoneNumexist(String phoneNumber , String userId){
		return this.systemUserPCDao.isPhoneNumexist(phoneNumber ,userId);
	}
	
	/**
	 * 根据用户id获取用户信息
	 * @param systemUserId 用户id
	 * @return
	 */
	public SystemUser getSystemUser(String systemUserId) {
		return this.systemUserPCDao.getSystemUser(systemUserId);
	}
	
	/**
	 * 根据用户id删除用户信息
	 * @param systemUserId 用户id
	 */
	public void delSystemUser(String systemUserId) {
		this.systemUserPCDao.delSystemUser(systemUserId);
	}
	
	/**
	 * 获取所有公司
	 * @param page
	 * @param rows
	 * @return
	 */
	public Pagination<Object> getAllCompany(int page, int rows ) {
		return this.systemUserPCDao.getAllCompany(page, rows );
	}
	
	/**
	 * 添加系统用户.
	 * @param userId 当前用户ID-添加人
	 * @param companyId 企业ID
	 * @param headshipId 岗位ID
	 * @param employeeId 员工ID
	 * @param userName 姓名
	 * @param mobile 手机号码
	 * @return String(用户ID)
	 */
	@Transactional
	public String addSystemUser(String userId, String companyId, String headshipId, String employeeId, String userName, String mobile) {
		SystemUser user = new SystemUser();
		user.setCompanyId(companyId);
		user.setHeadshipId(headshipId);
		user.setEmployeeId(employeeId);
		user.setUserName(mobile);
		String salt = UUIDUtil.generateUUID();//取密码盐
		String password = MD5Tools.encodePassword(Constant.PASS_WORD, salt);//得到加密后的密码,导入时默认密码111111
		user.setPassword(password);
		user.setPassSalt(salt);
		user.setMobile(mobile);
		user.setRealName(userName);
		user.setCreateMan(userId);
		user.setCreateTime(new Date());
		user.setDelFlag("0");
		return this.systemUserPCDao.save(user);
	}
}